<!-- 爱计划 -->
<template>
  <div class="a-plane">
    <div class="top">
      <div class="show-type">
        <div :class="{ active: showType === 'week' }" @click="changeShowType('week')">
          周
        </div>
        <div :class="{ active: showType === 'moth' }" @click="changeShowType('moth')">
          月
        </div>
        <div class="bottom-tag" :class="{
          'to-right': showType === 'moth',
          'to-left': showType === 'week'
        }"></div>
      </div>
      <div class="tools">
        <button type="button" class="btn btn-primary btn-sm btn-dark" @click="myJobs()">
          <i class="far fa-hand-point-right " aria-hidden="true"></i>
          这{{ showType === 'moth' ? '个月' : '周' }}都做了啥
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="addPlane('')">
          <i class="fa-solid fa-add " aria-hidden="true"></i>
          新建
        </button>
        <div class="btn-group" role="group" aria-label="Basic example">
          <button type="button" class="btn btn-primary btn-sm" @click="showDayReportFun('')">
            <i class="fa-solid fa-calendar-day " aria-hidden="true"></i>
            日报
          </button>
          <button type="button" class="btn btn-primary btn-sm" @click="showWeekReportFun('')">
            <i class="fa-regular fa-calendar-days " aria-hidden="true"></i>
            周报
          </button>
        </div>

        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="collapse" data-bs-target="#collapseReport"
          aria-expanded="false" aria-controls="collapseExample" @click="showReport = !showReport">
          <i class="fa-solid" :class="showReport ? 'fa-angle-down' : 'fa-angle-up'"></i>
          {{ showReport ? '展开' : '收起' }}报表
        </button>
      </div>
    </div>
    <div class="bottom" style="overflow-y: auto;padding: 0 10px;display: block;background-color: #000;">
      <div>
        <div class="collapse show" id="collapseReport">
          <div class="card card-body" style="border: none;background-color: #000;">
            <div style="display: flex;">
              <div ref="chart-time" style="width: 0;flex: 1;height: 300px;"></div>
              <div ref="chart-count" style="width: 0;flex: 1; height: 300px"></div>
            </div>
          </div>
        </div>
      </div>
      <!-- <div v-if="dateSort.length === 0">
        
      </div> -->
      <div v-for="key in dateSort" style="margin-bottom: 40px;margin-top: 20px;">
        <div class="sticky-top date-title"
          style="font-size: 1.2rem;font-weight: bold;color:var(--bs-primary);margin: 10px 0;z-index: 9;">
          {{ key }}
          <i class="fa-solid" :class="hidePlane[key] ? 'fa-angle-up' : 'fa-angle-down'" data-bs-toggle="collapse"
            :data-bs-target="`#collapse${key}`" aria-expanded="false" :aria-controls="`#collapse${key}`"
            @click="hidePlaneFun(key)" style="cursor: pointer;"></i>
        </div>
        <div v-if="planesMap[key]">
          <div v-for="typeKey in Object.keys(planesMap[key])" class="collapse show" :id="`collapse${key}`">
            <div class="d-title">
              {{ typeKey }}
            </div>
            <div v-for="plane in planesMap[key][typeKey]" class="d-item" @click="editPalneByForm(plane)">
              <div style="flex: 1;">
                <div style="font-weight: bold;">{{ plane.title }}</div>
                <div style="margin-top: 4px;" v-if="plane.detail">{{ plane.detail }}</div>
              </div>
              <div class="d-time" :class="plane.status === '已完成' ? 'd-finish' : ''">
                <i class="fa-regular fa-clock" style="margin-top: 2px;"></i>
                <div style="font-size: 0.6rem;margin-left: 8px">{{ plane.status }} &nbsp;&nbsp;{{ plane.time }}D</div>
              </div>
              <div class="d-status">
                {{ plane.scope }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-report" v-show="showDayReport" :style="{ opacity: showDayReportOpacity }">
      <div class="modal-dialog-centered" style="height: 100%;">
        <div class="modal-report-div">
          <div class="modal-report-top">
            <span class="copy-text" :style="{ opacity: showDayReportTxtOpacity }">已复制</span>
            <i class="fa fa-copy" @click="copyDayReport"> 拷贝</i>
            <i class="fa fa-close" @click="closeDayReportFun"></i>
          </div>
          <textarea id="dayReport"> </textarea>
        </div>
      </div>
    </div>

    <div class="modal-report" v-show="showWeekReport" :style="{ opacity: showWeekReportOpacity }">
      <div class="modal-dialog-centered" style="height: 100%;">
        <div class="modal-report-div" style="height: calc(100% - 200px);">
          <div class="modal-report-top">
            <span class="copy-text" :style="{ opacity: showWeekReportTxtOpacity }">已复制</span>
            <i class="fa-solid fa-paper-plane" @click="sendEmail"> 发周报</i>
            <i class="fa fa-copy" @click="copyWeekReport"> 拷贝</i>
            <i class="fa fa-close" @click="closeWeekReportFun"></i>
          </div>
          <textarea id="weekReport"> </textarea>
        </div>
      </div>
    </div>




    <div class="loading" :class="onload ? 'loading-show' : 'loading-hide'">
      <div class="icon">
        <i class="fa-solid fa-circle-notch "></i>
        <p>正在加载</p>
      </div>
    </div>

    <div id="jobsModal" class="modal" :class="showJobs ? 'modal-show' : ''">
      <div class="modal-dialog-centered" style="height: 100%;">
        <div class="modal-content">
          <div style="display: flex;margin-bottom: 10px;">
            <h3 style="flex: 1;" class="m-title">
              这段时间的工作内容
            </h3>
            <button type="button" class="btn-close" aria-label="Close" @click="showJobs = false"></button>
          </div>

          <div class="modal-body" style="white-space: pre-line;flex: 1;height: 0;overflow: auto">
            <p v-html="worksText"></p>
          </div>

          <div style="margin-top: 10px;text-align: right;">
            <button type="button" class="btn btn-primary" @click="toChat()">
              让AI总结一下
            </button>
            <button type="button" class="btn btn-primary" @click="toChatWith()">
              我想问问AI
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const schedule = require("node-schedule");
import Swal from "sweetalert2";
let ipcRenderer;
if (window.require) {
  ipcRenderer = window.require("electron").ipcRenderer;
}
const nedb = require("nedb");
import { globalBus } from "@/assets/js/globalBus.js";

export default {
  components: {},
  data() {
    return {
      //任务类型数据库
      aplaneTypeDb: undefined,
      //任务数据库
      aplaneTodoDb: undefined,
      //当前加载的数据库
      startLoadDate: {
        year: "",
        moth: "",
        date: "",
        week: ""
      },
      //当前加载的数据库
      endLoadDate: {
        year: "",
        moth: "",
        date: "",
        week: ""
      },
      showJobs: false,
      worksText: "",
      showType: "moth",
      dates: [],
      works: [],
      typeListMap: new Map(),
      chartTime: {},
      chartCount: {},
      hidePlane: {},
      showReport: false,
      planesMap: {}, //按日期分类的全部任务
      dateSort: [], //排序好的日期
      typeDate: {},
      choiceDate: {}, //当前日历选择的日期
      dbChoiceDate: {}, //当前db加载的日期
      showDayReport: false, //是否展示日报框
      showDayReportTxtOpacity: 0, //提示文字透明度
      showDayReportOpacity: 0, //拷贝弹窗显示透明度
      showWeekReportCall: false,
      showWeekReport: false, //是否展示周报框
      showWeekReportTxtOpacity: 0, //提示文字透明度
      showWeekReportOpacity: 0, //拷贝弹窗显示透明度
      onload: false, //是否正在加载
      alyxAPP: {
        title: "阿里邮箱",
        img: "./static/img/apps/email.jpg",
        icon: "./static/img/apps/email_icon.png",
        info: "阿里邮箱",
        url: "https://qiye.aliyun.com/alimail/",
        loginUrl: "https://qiye.aliyun.com/alimail/auth/login",
        type: "web",
        code: "alyx"
      }
    };
  },
  created() {
    globalBus.$on("aPlane_reload", this.reloadPlane);
    globalBus.$on("aPlane_changeShowTypeBack", this.changeShowTypeBack);
    globalBus.$on("aDate_changeDateBack", this.setChoceDate);
  },
  beforeDestroy() {
    globalBus.$off("aPlane_reload", this.reloadPlane);
    globalBus.$off("aPlane_changeShowTypeBack", this.changeShowTypeBack);
    globalBus.$off("aDate_changeDateBack", this.setChoceDate);
  },
  methods: {
    myJobs() {
      let text = ""
      let _this = this
      console.log(this.planesMap)
      Object.keys(this.planesMap).forEach(date => {
        Object.keys(this.planesMap[date]).forEach(key => {
          _this.planesMap[date][key].forEach(item => {
            text += `日期：${date}<br>工作内容：${item.title}<br>- 所属项目：${item.type}<br>- 类型：${item.scope}<br>- 耗时：${item.time}天<br>- 状态：${item.status}<br>- 备注：${item.detail}<br><br>`
          })
        })
      })
      this.worksText = text
      this.showJobs = true
    },
    toChatWith() {
      sessionStorage.setItem('chat-msg', this.worksText)
      globalBus.$emit("openApp", {
        type: 'app',
        name: 'chat',
        url: '/chat',
        query: { msg: true, ask: true }
      });
    },
    toChat() {
      let text = "以下是我的工作内容，帮我统计一下。\n" + this.worksText
      text += "汇总格式按照\n所属项目：xxx\n总耗时：x天"
      let title = "帮我汇总一下" + this.dateSort[this.dateSort.length - 1] + "至" + this.dateSort[0] + "的工作内容"
      sessionStorage.setItem('chat-msg', JSON.stringify({
        title: title,
        content: text
      }))
      globalBus.$emit("openApp", {
        type: 'app',
        name: 'chat',
        url: '/chat',
        query: { msg: true }
      });
    },
    reloadPlane() {
      this.startLoadDate = {};
      this.endLoadDate = {};
      this.changeShowType(this.showType);
      globalBus.$emit("aData_doTag", date => { });
    },
    setChoceDate(res) {
      this.choiceDate = res;
    },
    initChart() {
      let titleTimeMap = {} // 标题和耗时
      let titleTimes = [] // 标题和耗时
      let scopeTimeMap = {} // 类型和耗时
      let scopeTimes = [] // 类型和耗时

      let _this = this
      Object.keys(this.planesMap).forEach(date => {
        Object.keys(this.planesMap[date]).forEach(key => {
          _this.planesMap[date][key].forEach(data => {
            let time = titleTimeMap[key];
            if (time == undefined) {
              time = 0;
            }
            titleTimeMap[key] = time + data.time

            let time2 = scopeTimeMap[data.scope];
            if (time2 == undefined) {
              time2 = 0;
            }
            scopeTimeMap[data.scope] = time2 + data.time
          })
        })
      })
      Object.keys(titleTimeMap).forEach(key => {
        titleTimes.push({ value: titleTimeMap[key], name: key })
      })
      Object.keys(scopeTimeMap).forEach(key => {
        scopeTimes.push({ value: scopeTimeMap[key], name: key })
      })

      const optionTime = {
        backgroundColor: 'transparent', // 设置为透明 
        title: {
          text: this.showType === "moth" ? '月度工时报表' : '周报工时表',
          subtext: '当' + (this.showType === "moth" ? '月' : '周') + '工时分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: (r) => {
            return r.name +
              '<br/>' + '用时：' + r.value.toFixed(1) + "D" +
              '<br/>' + '比例：' + r.percent + '%'
          }
        },
        legend: {
          bottom: 0,
          type: 'scroll',
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: titleTimes,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      const optionCount = {
        backgroundColor: 'transparent', // 设置为透明 
        title: {
          text: this.showType === "moth" ? '月度计划报表' : '周报计划表',
          subtext: '当' + (this.showType === "moth" ? '月' : '周') + '计划分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: (r) => {
            return r.name +
              '<br/>' + '用时：' + r.value.toFixed(1) + "D" +
              '<br/>' + '比例：' + r.percent + '%'
          }
        },
        legend: {
          bottom: 0,
          type: 'scroll',
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: scopeTimes,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.chartTime.setOption(optionTime);
      this.chartCount.setOption(optionCount);
    },
    editPalneByForm(form) {
      globalBus.$emit("edit_plane_by_form", form);
    },
    getTdLeft(left, colspan) {
      return "calc(" + left * 100 + "%" + " + " + left + "px)";
    },
    sendEmail() {
      this.copyWeekReport();
      Swal.fire({
        title: `周报已拷贝-需要手动粘贴`,
        confirmButtonText: "明白！去发送"
      }).then(isConfirm => {
        if (isConfirm.isConfirmed) {
          globalBus.$emit("openApp", this.alyxAPP);
        }
      });
    },
    copyWeekReport() {
      let _this = this;
      let url = document.getElementById("weekReport");
      url.select(); // 选择对象
      document.execCommand("Copy");
      _this.showWeekReportTxtOpacity = 1;
      setTimeout(function () {
        _this.showWeekReportTxtOpacity = 0;
      }, 1500);
    },
    copyDayReport() {
      let _this = this;
      let url = document.getElementById("dayReport");
      url.select(); // 选择对象
      document.execCommand("Copy");
      _this.showDayReportTxtOpacity = 1;
      setTimeout(function () {
        _this.showDayReportTxtOpacity = 0;
      }, 1500);
    },
    hidePlaneFun(key) {
      this.$set(this.hidePlane, key, !this.hidePlane[key])
    },
    closeWeekReportFun() {
      let _this = this;
      _this.showWeekReportOpacity = 0;
      setTimeout(function () {
        _this.showWeekReport = false;
      }, 200);
    },
    closeDayReportFun() {
      let _this = this;
      _this.showDayReportOpacity = 0;
      setTimeout(function () {
        _this.showDayReport = false;
      }, 200);
    },
    addPlane() {
      globalBus.$emit("add_palne");
    },
    //日报
    showDayReportFun() {
      let _this = this;
      _this.showDayReport = true;
      setTimeout(function () {
        _this.showDayReportOpacity = 1;
      }, 50);

      let date = this.choiceDate;

      if (
        this.dbChoiceDate.year !== date.year ||
        this.dbChoiceDate.month !== date.moth
      ) {
        _this.aplaneTodoDb = new nedb({
          filename: "/data/aplane-todo_" + date.year + "-" + date.moth + ".db",
          autoload: true
        });
        _this.dbChoiceDate = {
          year: date.year,
          month: date.moth
        };
      }

      let dayReport = document.getElementById("dayReport");
      if (!_this.showDayReport || !dayReport) return;
      // 查询所有结果集
      _this.aplaneTodoDb.find(
        {
          year: date.year,
          moth: date.moth,
          date: date.date
        },
        function (err, docs) {
          let timeNow = new Date();
          let dayEndTag = timeNow.getHours() > 12;
          let allTxt = dayEndTag ? "今日完成\n" : "今日计划\n";
          let i = 0;
          docs.sort((a, b) =>
            (a.scope + a.type + a.sort + "").localeCompare(b.scope + a.type + b.sort + "")
          );
          for (let x in docs) {
            let time = docs[x].time ? parseFloat(docs[x].time) : 0;
            allTxt +=
              ++i +
              ". " +
              (docs[x].scope && docs[x].scope != '主线需求' && docs[x].scope != '定制开发' && docs[x].scope != '第三方对接' ? docs[x].scope + "：" : "") +
              (docs[x].type ? docs[x].type + "：" : "") +
              docs[x].title +
              (dayEndTag
                ? docs[x].status === "已完成"
                  ? "【已完成】"
                  : "【进行中】"
                : "") +
              " " +
              (time ? time + "d" : "") +
              "\n";
          }
          document.getElementById("dayReport").value = allTxt.trim();
        }
      );
    },
    //周报
    showWeekReportFun() {
      if (this.showType !== "week") {
        this.showWeekReportCall = true
        this.changeShowType("week");
        return;
      }
      this.showWeekReportCall = false
      let _this = this;
      let timeCountMap = new Map(); // 工时合并
      let timeProcessMap = new Map(); // 工时占比
      let allTime = 0; //总耗时
      let loopDates;
      let start = 0;
      let end = 7;

      let jsyf = [];
      let zxxq = [];
      let bug = [];
      let dzkf = [];
      let dwzc = [];
      let qt = [];
      let date =
        this.dates[0].year +
        "-" +
        this.dates[0].moth +
        "-" +
        this.dates[0].date;
      let ds = _this.planesMap[date];
      if (!ds || ds.length === 0) {
        start = 0;
      }
      date =
        this.dates[_this.dates.length - 1].year +
        "-" +
        this.dates[_this.dates.length - 1].moth +
        "-" +
        this.dates[_this.dates.length - 1].date;
      ds = _this.planesMap[date];
      if (!ds || ds.length === 0) {
        end = 7;
      }
      loopDates = _this.dates.slice(start, end);
      let allTxt = "";
      let hasZr = true;
      let hasZl = true;
      for (let x in loopDates) {
        let w;
        switch (parseInt(x) + start) {
          case 0:
            w = "日";
            break;
          case 1:
            w = "一";
            break;
          case 2:
            w = "二";
            break;
          case 3:
            w = "三";
            break;
          case 4:
            w = "四";
            break;
          case 5:
            w = "五";
            break;
          case 6:
            w = "六";
            break;
        }
        let text = ""
        let month = (loopDates[x].moth >= 9 ? loopDates[x].moth + 1 : '0' + (loopDates[x].moth + 1))
        let day = (loopDates[x].date >= 10 ? loopDates[x].date : '0' + loopDates[x].date)
        text +=
          "周" +
          w +
          "：\n";
        let date =
          loopDates[x].year + "-" + month + "-" + day;
        //每一天的工作内容
        let data = [];
        let i = 0;
        if (_this.planesMap[date]) {
          Object.keys(_this.planesMap[date]).forEach(key => {
            data = data.concat(_this.planesMap[date][key])
          })
        }

        if (data) {
          data.sort((a, b) =>
            (a.scope + a.type + a.sort + "").localeCompare(b.scope + a.type + b.sort + "")
          );
        }
        if (data.length == 0 && (w === '日' || w === '六')) {
          if (w === '日') {
            hasZr = false
          }
          if (w === '六') {
            hasZl = false
          }
          continue
        }
        for (let x in data) {
          let time = data[x].time ? parseFloat(data[x].time) : 0;

          text +=
            ++i +
            ". " +
            (data[x].scope && data[x].scope != '主线需求' && data[x].scope != '定制开发' && data[x].scope != '第三方对接' ? data[x].scope + "：" : "") +
            (data[x].type ? data[x].type + "：" : "") +
            data[x].title +
            (data[x].status === "已完成" ? "【已完成】" : "【进行中】") +
            " " +
            (time ? time + "d" : "") +
            "\n";

          let type = (data[x].type ? data[x].type + "：" : "")
          let timeCountKey;
          if (data[x].scope) {
            if (data[x].scope === "主线需求") {
              timeCountKey = (data[x].type ? data[x].type : data[x].scope) + "："
            } else if (data[x].scope === "定制开发" || data[x].scope === "第三方对接") {
              timeCountKey = data[x].scope + "："
            } else {
              timeCountKey = data[x].scope + "：" + type
            }
          } else {
            timeCountKey = type
          }

          let timeCount = timeCountMap.get(timeCountKey);
          if (timeCount === undefined) {
            if (data[x].scope === "技术研发") {
              jsyf.push(timeCountKey);
            } else if (data[x].scope === "主线需求") {
              zxxq.push(timeCountKey);
            } else if (data[x].scope === "Debug") {
              bug.push(timeCountKey);
              // zxxq.push(timeCountKey);
            } else if (data[x].scope === "定制开发") {
              dzkf.push(timeCountKey);
            } else if (data[x].scope === "对外支持") {
              dwzc.push(timeCountKey);
            } else {
              qt.push(timeCountKey);
            }
          }
          timeCount = timeCount ? timeCount : 0;
          timeCountMap.set(timeCountKey, timeCount + time);

          let timeProcess = timeProcessMap.get(data[x].scope);
          timeProcess = timeProcess ? timeProcess : 0;
          timeProcessMap.set(
            data[x].scope ? data[x].scope : "其他",
            timeProcess + time
          );

          allTime += time;
        }
        allTxt += text + "\n";
      }

      allTxt =
        "本周工作（" +
        (loopDates[hasZr ? 0 : 1].moth + 1) +
        "." +
        loopDates[hasZr ? 0 : 1].date +
        "~" +
        (loopDates[loopDates.length - (hasZl ? 1 : 2)].moth + 1) +
        "." +
        loopDates[loopDates.length - (hasZl ? 1 : 2)].date +
        "）\n" + allTxt;

      this.loadNextWeekPlane(text => {
        allTxt += "工时合并:\n";

        jsyf.sort();
        zxxq.sort();
        bug.sort();
        dzkf.sort();
        dwzc.sort();
        qt.sort();
        jsyf.forEach(v => {
          allTxt += v + timeCountMap.get(v).toFixed(1) + "d\n";
        });
        zxxq.forEach(v => {
          allTxt += v + timeCountMap.get(v).toFixed(1) + "d\n";
        });
        bug.forEach(v => {
          allTxt += v + timeCountMap.get(v).toFixed(1) + "d\n";
        });
        dzkf.forEach(v => {
          allTxt += v + timeCountMap.get(v).toFixed(1) + "d\n";
        });
        dwzc.forEach(v => {
          allTxt += v + timeCountMap.get(v).toFixed(1) + "d\n";
        });
        qt.forEach(v => {
          allTxt += v + timeCountMap.get(v).toFixed(1) + "d\n";
        });

        allTxt += "\n";
        allTxt += "下周计划:\n";
        allTxt += text;
        // allTxt += "\n";

        // allTxt += "本周工作时间占比:\n";
        // allTxt +=
        //   "1. 技术研发:\t\t" +
        //   Math.round(
        //     ((timeProcessMap.get("技术研发")
        //       ? timeProcessMap.get("技术研发")
        //       : 0) /
        //       allTime) *
        //     100
        //   ) +
        //   "%\n";
        // allTxt +=
        //   "2. 主线需求:\t\t" +
        //   Math.round(
        //     ((timeProcessMap.get("主线需求")
        //       ? timeProcessMap.get("主线需求")
        //       : 0) /
        //       allTime) *
        //     100
        //   ) +
        //   "%\n";
        // allTxt +=
        //   "3. bug:      \t\t" +
        //   Math.round(
        //     ((timeProcessMap.get("Debug") ? timeProcessMap.get("Debug") : 0) /
        //       allTime) *
        //     100
        //   ) +
        //   "%\n";
        // allTxt +=
        //   "4. 定制开发:\t\t" +
        //   Math.round(
        //     ((timeProcessMap.get("定制开发")
        //       ? timeProcessMap.get("定制开发")
        //       : 0) /
        //       allTime) *
        //     100
        //   ) +
        //   "%\n";
        // allTxt +=
        //   "5. 对外支持:\t\t" +
        //   Math.round(
        //     ((timeProcessMap.get("对外支持")
        //       ? timeProcessMap.get("对外支持")
        //       : 0) /
        //       allTime) *
        //     100
        //   ) +
        //   "%\n";
        // if (qt.length > 0) {
        //   allTxt +=
        //     "6. 其他:\t\t" +
        //     Math.round(
        //       ((timeProcessMap.get("其他") ? timeProcessMap.get("其他") : 0) /
        //         allTime) *
        //       100
        //     ) +
        //     "%\n";
        // }
        allTxt += "\n风险：无\n"
        allTxt += "问题：无\n"
        allTxt += "支持：无\n"
        document.getElementById("weekReport").value = allTxt.trim();
        _this.showWeekReport = true;
        setTimeout(function () {
          _this.showWeekReportOpacity = 1;
        }, 50);
      });
    },
    //加载下周计划
    loadNextWeekPlane(callBack) {
      let _this = this;
      let db = _this.aplaneTodoDb;
      let choiceDate = this.dates[6];
      let newDate = new Date(choiceDate.year, choiceDate.moth, choiceDate.date);
      let moth = choiceDate.moth;
      let text = "";
      let count = 0;
      let data = [];
      for (let x = 0; x <= 6; x++) {
        (function (xx) {
          newDate.setDate(newDate.getDate() + 1);
          if (newDate.getMonth() !== moth) {
            moth = newDate.getMonth();
            db = new nedb({
              filename:
                "/data/aplane-todo_" +
                newDate.getFullYear() +
                "-" +
                newDate.getMonth() +
                ".db",
              autoload: true
            });
          }
          db.find(
            {
              year: newDate.getFullYear(),
              moth: newDate.getMonth(),
              date: newDate.getDate()
            },
            function (err, res) {
              data = data.concat(res);
              if (xx === 6) {
                data = data.sort((a, b) =>
                  (a.scope + a.type).localeCompare(b.scope + b.type)
                );
                for (let x in data) {
                  text +=
                    ++count +
                    ". " +
                    (data[x].scope ? data[x].scope + "：" : "") +
                    (data[x].type ? data[x].type + "：" : "") +
                    data[x].title +
                    "\n";
                }
                callBack(text);
              }
            }
          );
        })(x);
      }
    },
    getFontSize(txt) {
      return txt.length > 10 ? "0.8rem" : "1rem";
    },
    //计算占据宽度 col自身比例  allCol总的宽比
    getTdWidth(col, allCol) {
      return "calc(" + col * 100 + "% - 10px)";
    },
    move(e) {
      //算出鼠标相对元素的位置
      let disX = e.clientX;
      let disY = e.clientY;
      let oldX = this.positionX;
      let oldY = this.positionY;
      document.onmousemove = e => {
        //鼠标按下并移动的事件
        //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        //绑定元素位置到positionX和positionY上面
        this.positionX = oldX + left;
        this.positionY = oldY + top;
      };
      document.onmouseup = e => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    },
    changeShowTypeBack(res) {
      let _this = this;
      if (_this.onload) {
        return;
      }
      _this.onload = true;

      _this.dates.splice(0, _this.dates.length);
      _this.works.splice(0, _this.works.length);
      _this.typeListMap.forEach(function (value, key) {
        value.splice(0, value.length);
      });

      if (this.showType === "moth") {
        if (
          _this.startLoadDate.year + "-" + _this.startLoadDate.moth !==
          res.year + "-" + res.moth
        ) {
          _this.aplaneTodoDb = new nedb({
            filename: "/data/aplane-todo_" + res.year + "-" + res.moth + ".db",
            autoload: true
          });
          _this.dbChoiceDate = {
            year: res.year,
            month: res.moth
          };
        }
        _this.startLoadDate = res;

        _this.aplaneTodoDb.find(
          {
            year: res.year,
            moth: res.moth
          },
          function (err, docs) {
            _this.onload = false;
            let map = {};// 按日期分类
            _this.dateSort = []
            docs.forEach(v => {
              let key = v.year + '-' + (v.moth >= 9 ? v.moth + 1 : '0' + (v.moth + 1)) + '-' + (v.date >= 10 ? v.date : '0' + v.date);

              if (map[key]) {
                if (map[key][v.type]) {
                  map[key][v.type].push(v)
                } else {
                  map[key][v.type] = [v]
                }
              } else {
                _this.dateSort.push(key)
                map[key] = {}
                map[key][v.type] = [v]
              }
              Object.keys(map[key]).forEach(k => {
                map[key][k].sort((a, b) =>
                  (a.scope + a.type + a.sort + "").localeCompare(b.scope + a.type + b.sort + "")
                );
              })
            })
            _this.dateSort.sort((a, b) => { return b.localeCompare(a) })
            _this.planesMap = map
            _this.initChart()
          })
      } else if (res.dates && res.dates.length > 0) {
        let loadDbYear = ''
        let loadDbMonth = ''
        let db;
        let allMap = {}
        _this.dateSort = []
        for (let i = 0; i < res.dates.length; i++) {
          let v = res.dates[i]
          if (loadDbYear != v.year || loadDbMonth != v.moth) {
            db = new nedb({
              filename:
                "/data/aplane-todo_" +
                v.year +
                "-" +
                v.moth +
                ".db",
              autoload: true
            });
            loadDbYear = v.year
            loadDbMonth = v.moth
          }
          ((v) => {
            db.find(
              {
                year: v.year,
                moth: v.moth,
                date: v.date,
              },
              (err, docs) => {
                if (docs.length > 0) {
                  let key = v.year + '-' + (v.moth >= 9 ? v.moth + 1 : '0' + (v.moth + 1)) + '-' + (v.date >= 10 ? v.date : '0' + v.date);
                  _this.dateSort.push(key)
                  allMap[key] = {}

                  docs.forEach(v => {
                    if (allMap[key][v.type]) {
                      allMap[key][v.type].push(v)
                    } else {
                      allMap[key][v.type] = [v]
                    }
                  })

                  Object.keys(allMap[key]).forEach(k => {
                    allMap[key][k].sort((a, b) =>
                      (a.scope + a.type + a.sort + "").localeCompare(b.scope + a.type + b.sort + "")
                    );
                  })
                }
                if (v.date === res.dates[res.dates.length - 1].date) {
                  _this.dateSort.sort((a, b) => { return b.localeCompare(a) })
                  _this.$set(_this, 'planesMap', allMap)
                  _this.initChart()
                }
              })
          })(v)
        }
        _this.dates = res.dates
        if (_this.showWeekReportCall) {
          _this.showWeekReportFun('')
        }
        _this.onload = false;
      } else {
        this.onload = false;
      }
    },
    changeShowType(type) {
      this.showType = type;
      globalBus.$emit("aDate_getDateList", type);
    },
  },
  mounted() {
    this.changeShowType("moth");
    this.$nextTick(function () {
      this.chartTime = this.$echarts.init(this.$refs['chart-time'], 'dark'); //this.$store.state.theme.themeType
      this.chartCount = this.$echarts.init(this.$refs['chart-count'], 'dark'); //this.$store.state.theme.themeType
      window.addEventListener("resize", () => {
        this.chartTime.resize();
        this.chartCount.resize();
      });
    });
    if (ipcRenderer) {
      schedule.scheduleJob("30 0 17 * * *", () => {
        ipcRenderer.send("show-notification", {
          title: "爱工作-提醒",
          body: "快下班啦！记得发送日报哦！"
        });
      });
    }
  }
};
</script>

<style lang="less" scoped>
@keyframes toRightKF {
  0% {
    left: 0;
    width: 2rem;
  }

  50% {
    left: 0%;
    width: 4rem;
  }

  100% {
    left: 50%;
    width: 2rem;
  }
}

@keyframes toLeftKF {
  0% {
    left: 50%;
    width: 2rem;
  }

  50% {
    left: 0%;
    width: 4rem;
  }

  100% {
    left: 0;
    width: 2rem;
  }
}

.theme-dark {
  .a-plane {
    background: #000000;
    color: #fff;

    .date-title {
      background: #000000;
    }

    .modal-report {
      background: rgba(50, 50, 50, 0.5);

      .modal-report-div {
        background: #232327;

        textarea {
          color: #fff;
        }
      }
    }

    .d-title {
      color: #90abc9;
    }

    .d-item {
      background: #232327;

      .d-status {
        background: #468abe;
        color: #fff;
      }

      .d-time {
        background: #2c3b4b;
        color: #1687ff;
      }

      .d-time.d-finish {
        background: #225732c7;
        color: #1ece18;
      }
    }
  }
}

.theme-light {
  .a-plane {
    background: #eeeeee;

    .date-title {
      background: #eeeeee;
    }

    .modal-report {

      background: rgba(0, 0, 0, 0.3);

      .modal-report-div {
        background: #ffffff;

        textarea {
          color: #607d8b;
        }
      }
    }

    .d-item {
      background: #fff;

      .d-status {
        background: #69bfff;
        color: #fff;
      }

      .d-time {
        background: #e7f5ff;
        color: #1687ff;
      }
    }

    .d-title {
      color: #425365;
    }

  }
}


.a-plane {
  height: 100%;
  box-sizing: border-box;
  display: flex;
  padding: 14px;
  flex-direction: column;

  .modal-report {
    transition: all 0.2s ease-in-out;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    padding-left: 60px;
    z-index: 999;

    .modal-report-div {
      width: 700px;
      max-width: calc(100% - 60px);
      height: 500px;
      margin: 100px auto;
      border-radius: 4px;
      box-sizing: border-box;
      padding: 20px;
      display: flex;
      flex-direction: column;

      textarea {
        margin-top: 10px;
        width: 100%;
        flex: 1;
        border: none;
        outline: none;
        resize: none;
        color: #607d8b;
        background: transparent;
      }

      .modal-report-top {
        text-align: right;

        i {
          margin-left: 10px;
          cursor: pointer;
          color: #607d8b;
        }

        i:hover {
          color: #03a9f4;
        }

        .copy-text {
          transition: all 0.2s ease-in-out;
          font-size: 0.8rem;
          color: #7092a2;
          opacity: 0;
        }
      }
    }
  }

  .bottom {
    width: 100%;
    flex: 1;
    padding-top: 4px;
    overflow: hidden;

    .d-title {
      margin-left: 10px;
      font-size: 1rem;
      font-weight: bold;
    }

    .d-item {
      cursor: pointer;
      font-size: 0.8rem;
      margin: 10px 0;
      border-radius: 14px;
      padding: 10px 20px;
      display: flex;
      align-items: center;
      margin-left: 10px;

      .d-status {
        font-size: 0.6rem;
        padding: 6px 16px;
        border-radius: 20px
      }

      .d-time {
        font-size: 0.8rem;
        font-weight: bold;
        padding: 4px 10px;
        border-radius: 20px;
        margin-right: 16px;
        display: flex;
        align-items: center
      }
    }

  }

  .top {
    padding-bottom: 10px;
    display: flex;
    color: #90a4ae;

    .tools {
      flex: 1;
      text-align: right;

      .item {
        display: inline-flex;
        line-height: 1rem;
        cursor: pointer;
        margin-left: 10px;
        transition: all 0.2s linear;

        div {
          font-size: 0.8rem;
          margin-left: 4px;
          transition: all 0.2s linear;
          display: inline-block;
          width: 0px;
          overflow: hidden;
          white-space: nowrap;
        }
      }

      .item:hover {
        color: #1e88e5;

        div {
          //width: 3.2rem;
        }
      }
    }

    .show-type {
      margin-top: 0.2rem;
      height: 1.4rem;
      display: flex;
      position: relative;

      .to-right {
        animation: toRightKF 0.5s;
        animation-fill-mode: forwards;
      }

      .to-left {
        animation: toLeftKF 0.5s;
        animation-fill-mode: forwards;
      }

      .bottom-tag {
        border-radius: 4px;
        height: 3px;
        width: 2rem;
        background: var(--bs-primary);
        position: absolute;
        bottom: -4px;
      }

      div {
        width: 2rem;
        cursor: pointer;
        text-align: center;
        line-height: 1.2rem;
        transition: all 0.1s linear;
      }

      div:hover {
        color: var(--bs-primary);
      }

      .active {
        font-weight: bold;
        font-size: 1.2rem;
        color: var(--bs-primary);
        width: 2rem;
        //  border-bottom: 3px #1E88E5 solid;
        padding-bottom: 4px;
      }
    }
  }
}


.a-plane {

  .modal.modal-show {
    z-index: 99;
    opacity: 1;
  }

  .modal {
    z-index: -1;
    opacity: 0;
    display: block;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;

    .modal-content {
      width: 600px;
      margin: 0 auto;
      padding: 30px;
      box-sizing: border-box;
      border-radius: 10px;
      max-height: calc(100% - 100px);
      display: flex;
      flex-direction: column;
    }


  }
}
</style>
